import BaseSprite from "../../../Script/Base/BaseSprite";
import EventID from "../../../Script/Common/EventID";
import { GlobalData } from "../../../Script/Common/GlobalData";
import { IMessage, IStoreData, IStoreItem } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../Util/StorageUtil";
import StoreItem from "./StoreItem";
import StoreUI from "./StoreUI";

const { ccclass, property } = cc._decorator;

// 小卖店玩法---货架补货
@ccclass
export default class Counter extends BaseSprite implements IMessage {

    @property({ type: cc.Node, tooltip: "" })
    private upItems: cc.Node = null;
    @property({ type: cc.Node, tooltip: "" })
    private downItems: cc.Node = null;

    @property({ type: cc.Node, tooltip: "" })
    private itemUp: cc.Node = null;
    @property({ type: cc.Node, tooltip: "" })
    private itemDown: cc.Node = null;

    @property({ type: cc.Node, tooltip: "rect" })
    private rect: cc.Node = null;

    private select: IStoreItem = null;

    private storeData: IStoreData = null;

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    public getCounterItems() {
        return this.upItems;
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        this.storeData = StorageUtil.instance.getStoreData();
    }

    protected onEnable() {
        this.upItems.on(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.upItems.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.upItems.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.upItems.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }
    protected onDisable() {
        this.upItems.off(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.upItems.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.upItems.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.upItems.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    public refreshUI() {
        this.upItems.children.forEach((o, i) => {
            let upItem = this.storeData.upItems.find((o1) => o1.counterId === i + 1);
            let node = o.children[0];
            if (!node && upItem.item.id > -1) {
                node = cc.instantiate(this.itemUp);
                node.parent = o;
            }
            if (upItem.item.num <= 0) {
                node?.destroy();
            }
            node?.getComponent(StoreItem).setData('up', upItem.item, false);
        });
        this.downItems.children.forEach((o, i) => {
            let itemId = i + 10101;
            let item = this.storeData.downItems.find((o1) => o1.id === itemId) || { id: itemId, num: 0 };
            let node = o.children[0];
            if (!node) {
                node = cc.instantiate(this.itemDown);
                node.parent = o;
            }
            node.getComponent(StoreItem).setData('down', item, false, () => {
                this.select = item;
            });
        });
    }

    private addUpItem(parent: cc.Node, counterId: number) {
        if (!this.select) return;
        if (this.select.num <= 0) return;

        const oldNode = parent.children[0];
        if (oldNode) {
            const oldComp = oldNode.getComponent(StoreItem);
            const oldData = oldComp.getRewardData();
            if (oldData.id === this.select.id && oldData.num === 5) {
                return;
            }
            // 把老数据加回去
            StoreUI.instance.refreshData(oldData.id, oldData.num);
            // 设置新数据
            this.setCounterData(oldComp, counterId);
        } else {
            const node = cc.instantiate(this.itemUp);
            node.parent = parent;
            const newComp = node.getComponent(StoreItem);
            this.setCounterData(newComp, counterId);
        }
        // 刷新展示
        this.refreshUI();
    }

    /** 放置时设置库存数量  默认每次放置最大为5个 */
    private setCounterData(comp: StoreItem, counterId: number) {
        const kucun = StoreUI.instance.getStoreDataById(this.select.id);
        const upItem = this.storeData.upItems.find((o)=>o.counterId === counterId);
        if (kucun.num >= 5) {
            upItem.item = {id: this.select.id, num: 5};
            comp.setData('up', { id: this.select.id, num: 5 }, true);
            StoreUI.instance.refreshData(this.select.id, -5);
        } else {
            upItem.item = {id: this.select.id, num: kucun.num};
            comp.setData('up', { id: this.select.id, num: kucun.num }, true);
            StoreUI.instance.refreshData(this.select.id, -kucun.num);
        }
        StoreUI.instance.updateCounterInfo();
    }

    private onTouchDown(event: cc.Event.EventTouch, data: string) {
        const scale = SceneGame.instance.getRootScale();
        const pos = event.getLocation();
        this.rect.x = (pos.x - GlobalData.stage_width / 2) / scale;
        this.rect.y = (pos.y - GlobalData.stage_height / 2) / scale;
    }
    private onTouchMove(event: cc.Event.EventTouch, data: string) {
        const scale = SceneGame.instance.getRootScale();
        const pos = event.getLocation();
        this.rect.x = (pos.x - GlobalData.stage_width / 2) / scale;
        this.rect.y = (pos.y - GlobalData.stage_height / 2) / scale;

        for (let i = 0; i < this.upItems.children.length; i++) {
            const node = this.upItems.children[i];
            const intersect = GameUtil.intersect(node, this.rect);
            if (intersect) {
                // console.log("i:", i);
                this.addUpItem(node, i + 1);
            }
        }
    }
    private onTouchEnd(event: cc.Event.EventTouch, data: string) { }
    private onTouchCancel(event: cc.Event.EventTouch, data: string) { }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnCounter':
                {
                    StoreUI.instance.openOtherNode(1);
                }
                break;
        }
    }
}